﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.Xml;
using Cinchoo.Core.Services;
using System.Collections;
using System.IO;
using Cinchoo.Core;
using Cinchoo.Core.Xml.Serialization;
using System.Runtime.Serialization;

namespace Cinchoo.Core.Configuration
{
    public class ChoFileJSONSerializerConfigStorage : ChoFileDictionaryConfigStorage, IChoDictionaryConfigStorage
    {
        public override object Load(ChoBaseConfigurationElement configElement, XmlNode node)
        {
            base.Load(configElement, node);

            if (IsAppConfigFile)
                throw new ChoConfigurationException("Missing Json data file path.");

            string jsonPayload = null;
            if (File.Exists(this.ConfigFilePath))
                jsonPayload = File.ReadAllText(ConfigFilePath);
            else
                configElement[ChoConfigurationConstants.FORCE_PERSIST] = true;

            configElement["prevDict"] = null;
            if (!jsonPayload.IsNullOrWhiteSpace())
            {
                IChoConfigStoragePayloadSerializer ser = (IChoConfigStoragePayloadSerializer)configElement.StateInfo["ConfigStoragePayloadSerializer"];
                if (ser == null)
                    ser = ChoConfigStorageJSONPayloadSerializer.Instance;
                if (ser != null)
                {
                    configElement["prevDict"] = ser.Deserialize(jsonPayload);
                    return configElement["prevDict"];
                }
            }

            return null;
        }

        protected override void PersistConfigData(object data, ChoDictionaryService<string, object> stateInfo)
        {
            if (!(data is IDictionary))
                throw new ChoConfigurationException("Data object is not IDictionary object.");
            if (IsAppConfigFile)
                throw new ChoConfigurationException("Missing Json data file path.");

            Dictionary<string, object> srcDict = (Dictionary<string, object>)data;
            Dictionary<string, object> destDict = (Dictionary<string, object>)stateInfo["prevDict"];

            if ((bool)stateInfo[ChoConfigurationConstants.FORCE_PERSIST] || destDict == null || !srcDict.SequenceEqual(destDict))
            {
                stateInfo["prevDict"] = srcDict;

                IChoConfigStoragePayloadSerializer ser = (IChoConfigStoragePayloadSerializer)stateInfo["ConfigStoragePayloadSerializer"];
                if (ser == null)
                    ser = ChoConfigStorageJSONPayloadSerializer.Instance;
                if (ser != null)
                    File.WriteAllText(ConfigFilePath, ser.Serialize(srcDict) as string);
            }
        }

        public override bool IsCustomFormatDataStorage
        {
            get { return true; }
        }
    }
}